# -*- coding: utf-8 -*-
"""
Created on Sun Aug 25 11:52:41 2024

@author: ZHOU
"""
import threading
import time

from pynput import mouse, keyboard  
import pydirectinput 

global m  
m = mouse.Controller()
global move_flag
move_flag=0
global quit_flag
quit_flag = 0
global mode
mode = 0


def callback(k,li):
    pass
    
def on_mouse_move(x, y):  
    pass
#    print(f'鼠标移动到位置: ({x}, {y})')  

def on_mouse_click(x, y, button, pressed):  
    global move_flag
    global mode
    s=str(button)
    if pressed:          
        if mode:
            if s=="Button.left":
                li=m.position        
                m.position=(li[0],0)
                move_flag = 1
        elif s=="Button.x2" or s=="Button.x1":
            mode = 1
    else:  
        if s=="Button.left":
            move_flag = 0
            mode = 0
#        print(f'{button} 释放于位置: ({x}, {y})') 
        
def on_mouse_scroll(x, y, dx, dy):
    pass
    # dx 和 dy 表示滚动的水平方向和垂直方向的量  
    # 在大多数鼠标上，只有 dy 会变化，表示垂直滚动  
#    print(f'Scrolled at {x}, {y} ({dx}, {dy})')  
 
 
def on_key_press(key):
    callback(str(key),[]);
  
def release_callback(k):
    global move_flag
    global quit_flag
    if k=="'j'":
       quit_flag=1
       move_flag=0
        
def on_key_release(key):  
    release_callback(str(key))
#    try:  
#        print(f'{key.char} 被释放')  
#    except AttributeError:  
#        print(f'{key} 被释放')  
  
global mouse_listener
global keyboard_listener
# 创建鼠标监听器  
mouse_listener = mouse.Listener(on_move=on_mouse_move, on_click=on_mouse_click,on_scroll=on_mouse_scroll)  

# 创建键盘监听器，同时监听按下和释放事件  
keyboard_listener = keyboard.Listener(on_press=on_key_press, on_release=on_key_release)  

def key_start():
    global mouse_listener
    global keyboard_listener
    mouse_listener.start() 
    keyboard_listener.start() 
    mouse_listener.join()  
    keyboard_listener.join() 
    
global t
t=threading.Thread(target=key_start)
t.setDaemon(True)
t.start()    

def down():
    pydirectinput.move(None,3)
    
def move_while():
    global move_flag
    global quit_flag
    global mode
    while quit_flag==0:
        time.sleep(0.01)
        while move_flag and mode:            
            time.sleep(0.01)   
            th=threading.Thread(target=down)
            th.setDaemon(True)
            th.start()
#            li=m.position            
#            x=li[0]
#            y=li[1]
#            print(x,y)
#            m.position=(x,y+delta)


def main():
    global mouse_listener
    global keyboard_listener
    print("先按鼠标侧键开启压枪 然后长按左键即可")
    print("按J退出程序")
#    key_start()
    move_while()
    keyboard_listener.stop()
    mouse_listener.stop()
    print("quit")

    
if __name__ == '__main__':
    main()
   